package com.zb.service.impl;

import com.zb.service.LogService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class RedisLogServiceImpl implements LogService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${data-generator.redis-log-key}")
    private String logKey;

    // 最大日志条数
    private static final int MAX_LOG_COUNT = 10000;

    @Override
    public void addLog(String message) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String logMessage = "[" + timestamp + "] " + message;
        
        // 添加到Redis列表左侧
        redisTemplate.opsForList().leftPush(logKey, logMessage);
        
        // 限制列表长度
        redisTemplate.opsForList().trim(logKey, 0, MAX_LOG_COUNT - 1);
    }

    @Override
    public List<String> getLatestLogs(int count) {
        // 从Redis获取最新的count条日志
        List<String> logs = redisTemplate.opsForList().range(logKey, 0, count - 1);
        return logs != null ? logs : new ArrayList<>();
    }

    @Override
    public void clearLogs() {
        redisTemplate.delete(logKey);
    }
}
